<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="fn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(item, index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
    <div>当前处于{{ editMode ? "编辑" : "添加" }}模式</div>
    <div v-if="editMode">正在编辑序号为{{ this.id }}的学生的信息</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: "",
      age: 0,
      gender: "",
      list: JSON.parse(localStorage.getItem("list")) || [],
      id: 0,
      editMode: false,
    };
  },
  methods: {
    fn() {
      if (
        this.name == "" ||
        this.age <= 0 ||
        typeof this.age != "number" ||
        this.gender == ""
      ) {
        alert("非法输入！");
        return;
      }
      let index = this.list.findIndex((item) => item.id == this.id);
      if (index == -1) {
        if (this.editMode) {
          alert("您想修改的学生数据不存在！");
          this.editMode = false;
          this.id = 0;
          return;
        }
        this.list.push({
          id: this.list.length > 0 ? this.list[this.list.length - 1].id + 1 : 1,
          name: this.name,
          age: this.age,
          gender: this.gender,
        });
        this.id = 0;
        return;
      }
      this.list[index].name = this.name;
      this.list[index].age = this.age;
      this.list[index].gender = this.gender;
      this.id = 0;
      this.editMode = false;
    },
    del(index) {
      this.list.splice(index, 1);
    },
    edit(item, index) {
      this.editMode = true;
      this.id = item.id;
      this.name = this.list[index].name;
      this.age = this.list[index].age;
      this.gender = this.list[index].gender;
    },
  },
  watch: {
    list(newVal) {
      localStorage.setItem("list", JSON.stringify(newVal));
    },
  },
};
</script>